import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:speech_to_text/speech_to_text.dart';

class STTUtil {
  STTUtil._();
  static final STTUtil _manager = STTUtil._();
  factory STTUtil() {
    return _manager;
  }
  static final SpeechToText speechToText = SpeechToText();
  static bool available = false;

  static init() async {
    available = await speechToText.initialize();
  }

  static listen(ValueChanged<String> onChanged) {
    if (available) {
      speechToText.listen(
        onResult: (result) {
          onChanged.call(result.recognizedWords);
          cancel();
          listen(onChanged);
        },
        localeId: 'zh_CN',
        listenFor: const Duration(seconds: 60),
        listenOptions: SpeechListenOptions(
          cancelOnError: true,
        ),
      );
    } else {
      SmartDialog.showToast('语音转文本初始化失败',displayType: SmartToastType.last);
    }
  }

  static cancel() {
    speechToText.cancel();
  }
}